package dept

import (
	"context"
	"go-zero-project/services/user/rpc/pb"

	"go-zero-project/services/user/api/internal/svc"
	"go-zero-project/services/user/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type SubListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewDeptSubListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SubListLogic {
	return &SubListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *SubListLogic) DeptSubList(req *types.DeptListReq) (resp *types.DeptListResp, err error) {
	// 1.builder rpc request
	infoReq := pb.DeptListReq{DeptId: req.DeptId}
	// 2.request rpc
	subListResp, err := l.svcCtx.UserCenterClient.DeptSubList(l.ctx, &infoReq)
	if err != nil {
		return nil, err
	}
	// 3.return obj
	resp = new(types.DeptListResp)
	resp.DeptId = subListResp.DeptId
	resp.Name = subListResp.Name
	resp.OrderNum = int(subListResp.OrderNum)
	resp.ParentName = subListResp.ParentName
	resp.ParentId = subListResp.ParentId
	looperErr := l.looper(resp, subListResp)
	if looperErr != nil {
		return nil, looperErr
	}
	return resp, nil
}

func (l *SubListLogic) looper(resp *types.DeptListResp, subListResp *pb.DeptListResp) error {
	subList := subListResp.SubList
	if len(subList) < 1 {
		return nil
	}
	var itemList []types.DeptListResp
	for _, v := range subList {
		item := types.DeptListResp{
			DeptId:     v.DeptId,
			Name:       v.Name,
			ParentId:   v.ParentId,
			ParentName: v.ParentName,
			OrderNum:   int(v.OrderNum),
		}
		lopperErr := l.looper(&item, v)
		if lopperErr != nil {
			return nil
		}
		itemList = append(itemList, item)
	}
	resp.SubList = itemList
	return nil
}
